<template>
	<div class="chatInterface" >
		<div class="header">
			{{group.name}}
			<image class="group-icon" src="/static/images/group-icon.png" @click="showMembers" />
		</div>
		<div class="chat-scroll-container">
			<scroll-view ref="myScroll" scroll-y="true" class="scroll-view" :scroll-into-view="contentPosition">
				<div :class="[allHistoryLoaded ? 'top gray' : 'top']" @click="loadMoreHistoryMessage">
					<span>{{allHistoryLoaded ? '已经没有更多的历史消息' : '点击加载更多历史消息'}}</span>
				</div>
				<!--已经收到的消息-->
				<div v-for="(message, key) in messages || []"
					 :id="'message_' + message.timestamp"
					 :key="message.timestamp"
					 class = "message-item"
					 :class="{'self' : message.senderId == (currentUser && currentUser.uuid)}">
					<div class="avatar">
						<image :src="currentUser.avatar" v-if="message.senderId == currentUser.uuid"></image>
						<image :src="groupMember.users[message.senderId].avatar" v-else></image>
					</div>
					<div class="content">
						<span class="text-content" v-if="message.type =='text'">{{message.payload.text}}</span>
						<image class="image-content" v-if="message.type == 'image'" :src="message.payload.url" :data-url="message.payload.url" @click="showImageFullScreen" mode="widthFix" @load="scrollToBottom"></image>
						<div class="video-snapshot"  v-if="message.type == 'video'" :data-url="message.payload.video.url" @click="playVideo">
							<image :src="message.payload.thumbnail.url" mode="aspectFit" @load="scrollToBottom"></image>
							<div class="video-play-icon"></div>
						</div>
						<GoEasyAudioPlayer v-if="message.type =='audio'" :src="message.payload.url" :duration="message.payload.duration" />
					</div>
				</div>
				<!--发送中的消息-->
				<div v-for="(message, index) in pendingMessages || []"
					 :key="index"
					 :id="'pendingMessage_' + index"
					 class = "message-item"
					 :class="{'self' : message.senderId == (currentUser && currentUser.uuid)}">
					<div class="avatar">
						<image :src="currentUser.avatar" v-if="message.senderId == currentUser.uuid"></image>
						<img :src="groupMember.users[message.senderId].avatar" v-else>
					</div>
					<div class="content">
						<b class="pending"></b>
						<span v-if="message.type =='text'">{{message.payload.text}}</span>
						<img v-if="message.type == 'image'" :src="message.payload.url" @load="scrollToBottom">
						<div v-if="message.type == 'video'" class="video-snapshot">
							<video :src="message.payload.video.url"></video>
							<div class="video-play-icon"></div>
						</div>
						<GoEasyAudioPlayer v-if="message.type =='audio'" :src="message.payload.url" :duration="message.payload.duration" />
					</div>
				</div>
			</scroll-view>
		</div>
		<div class="action-box" v-if="!video.visible">
			<div class="action-top">
				<div :class="[audio.visible ? 'record-icon record-open':'record-icon']" @click="switchAudioKeyboard"></div>
				<div class="record-input" @longpress="onRecordStart" @touchend="onRecordEnd" v-if="audio.visible" >{{audio.recording ? '松开发送' : '按住录音'}}</div>
				<div class="message-input" v-else>
					<input type="text" placeholder="发送消息" v-model="content">
				</div>
				<div class="file-icon img-video" @click="sendImage"></div>
				<div class="file-icon" @click="sendVideo"></div>
				<span class="send-message-btn" @click="sendMessage">发送</span>
			</div>
		</div>
		<!-- 群成员列表界面 -->
		<view class="member-layer" v-show="groupMember.show">
			<view class="header layer-header">
				<span class="back-btn" @click="groupMember.show = false"> </span>
				群成员({{Object.keys(groupMember.users).length}})
			</view>
			<view class="member">
				<image :src="member.avatar"
					   class="group-member__item"
					   v-for="(member, key) in groupMember.users"
					   :key="key">
				</image>
			</view>
		</view>
		<div class="record-loading" v-if="audio.recording"></div>
		<video style="width:100%;height: 100%" :src="video.url" v-if="video.visible" id="videoPlayer" autoplay="true" @fullscreenchange="onVideoFullScreenChange"  @play="onVideoPlayStart"></video>
	</div>
</template>

<script>
	import GoEasyAudioPlayer from "../../components/GoEasyAudioPlayer/GoEasyAudioPlayer";
	const recorderManager = uni.getRecorderManager();
	export default {
		name: "groupChat",
		components : {
			GoEasyAudioPlayer,
		},
		data () {
			return {
				//聊天文本框
				content: '',
				group:null,
				currentUser: null,
				groupMember : {
					users : {},
					show : false
				},
				//已经接收到的消息
				messages: [],
				//正在发送中的消息
				pendingMessages : [],
				//已经加载完所有历史消息
				allHistoryLoaded: false,

				contentPosition : '',

				audio : {
					//语音录音中
					recording : false,

					//录音按钮展示
					visible : false
				},
				video : {
					visible : false,
					url : '',
					context : null
				}
			}
		},
		watch : {
			pendingMessages(){
				this.scrollToBottom()
			}
		},
		onReady () {
			this.video.context = uni.createVideoContext('videoPlayer');
		},
		onLoad(options) {
			if(!this.imService.currentUser){
				uni.navigateTo({
					url : '../login/login'
				});
			}
			
			//对话数据
			this.group = JSON.parse(options.group);
			this.currentUser = this.imService.currentUser;
			let privateMessages = this.imService.getGroupMessages(this.group.uuid);
			this.messages = privateMessages.sentMessages;
			this.pendingMessages = privateMessages.pendingMessages;
			this.groupMember.users = this.imService.getGroupMembers(this.group.uuid);
			setTimeout(() => {
				uni.setNavigationBarColor({
					backgroundColor : '#D02129',
					frontColor : '#ffffff'
				});
			}, 10);
			
			this.initialListeners();
			
			//每次进入聊天页面，总是滚动到底部
			this.scrollToBottom()
		},
		onUnload() {
			//退出聊天页面之前，清空页面传入的监听器
			this.imService.onNewGroupMessageReceive =  (groupId, message)=> {};
			this.imService.onGroupHistoryLoad = (groupId, messages) =>{ };
			this.imService.resetGroupUnReadMessage(this.group);//清空未读消息
		},
		methods : {
			initialListeners(){
				//传入监听器，收到一条私聊消息总是滚到到页面底部
				this.imService.onNewGroupMessageReceive =  (groupId, message)=> {
					if (groupId == this.group.uuid) {
						//收到新消息，是滚动到最底部
						this.scrollToBottom();
					}
				};
				
				//传入监听器，完成一次私聊历史加载时，如果加载结果为空，显示没有更多消息
				this.imService.onGroupHistoryLoad = (groupId, messages) =>{
					if (messages.length == 0) {
						//todo:灰色，就不能点击了
						this.allHistoryLoaded = true;
					}
				};
				
				// 录音监听器
				this.initRecorderListeners();
			},
			initRecorderListeners(){
				var self = this;
				// 监听录音开始
				recorderManager.onStart(function(){
					console.log("onStart");
					self.audio.recording = true;
				});
				
				//录音结束后，发送
				recorderManager.onStop(function(res){
					console.log("onStop");
					self.audio.recording = false;
					self.imService.sendGroupAudioMessage(self.group.uuid, res)
				});
				
				// 监听录音报错
				recorderManager.onError(function(res){
					console.log("录音报错：",res);
				})
			},
			sendMessage () {//发送消息
				if(this.content.trim() != "") {
					this.imService.sendGroupTextMessage(this.group.uuid, this.content);
				}
				this.content = "";
			},
			loadMoreHistoryMessage () {//历史消息
				let lastMessageTimeStamp = Date.now();
				let lastMessage = this.messages[0];
				if (lastMessage) {
					lastMessageTimeStamp = lastMessage.timestamp;
				}
				this.imService.loadGroupHistoryMessage(this.group.uuid, lastMessageTimeStamp);
			},
			showMembers () {//显示群成员
				this.groupMember.show = true;
			},
			onRecordStart () {
				try{
					recorderManager.start();
				}catch(e){
					console.log("e:",e);
					uni.showModal({
						title: '录音错误',
						content : '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
					});
				}
			},
			onRecordEnd () {
				try{
					recorderManager.stop();
				}catch(e){
					console.log("e:",e);
					uni.showModal({
						title: '录音错误',
						content : '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
					});
				}
			},
			sendVideo () {//发送文件
				uni.chooseVideo({
					success : (res) => {
						console.log(res)
						this.imService.sendGroupVideoMessage(this.group.uuid, res)
					}
				})
			},
			sendImage() {
				uni.chooseImage({
					count :1,
					success :(res) => {
						console.log(res)
						this.imService.sendGroupImageMessage(this.group.uuid,res);
					}
				})
			},
			showImageFullScreen (e) {
				var imagesUrl = [e.currentTarget.dataset.url];
				uni.previewImage({
					urls: imagesUrl
				});
			},
			//语音录制按钮和键盘输入的切换
			switchAudioKeyboard() {
				this.audio.visible = !this.audio.visible;
			},
			playVideo (e) {
				this.video.visible = true;
				this.video.url = e.currentTarget.dataset.url;
			},
			onVideoPlayStart () {
				this.video.context.requestFullScreen({
					direction : 0
				});
			},
			onVideoFullScreenChange (e) {
				//当退出全屏播放时，隐藏播放器
				if(this.video.visible && !e.detail.fullScreen){
					this.video.visible = false;
					this.video.context.stop();
				}
			},
			scrollToBottom () {
				this.$nextTick(() => {
					if(this.messages && this.messages.length !=0){
						this.contentPosition = 'message_' + (this.messages[this.messages.length-1].timestamp || '');
					}
				})
			}
		}
	}
</script>

<style>
	@import url("../../static/style/chatInterface.css");
	page {
		height: 100%;;
	}

	uni-page-body {
		height: 100%;;
	}
	.chatInterface{
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		overflow-x: hidden;
	}
	.chatInterface .header{
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 36rpx;
		background: linear-gradient(0deg, #D02129, #D02129), linear-gradient(195.96deg, #F33A3A 9.83%, #D02129 105.7%);
		display: flex;
		color: #ffffff;
		justify-content: center;
		align-content: flex-start;
	}
	.chatInterface .back-btn{
		position: absolute;
		left: 20rpx;
	}
	.chatInterface .group-icon{
		right: 20rpx;
		width: 60rpx;
		height: 60rpx;
		top:14rpx
	}
	.chatInterface .chat-scroll-container{
		overflow: hidden;
		padding-left: 20rpx;
		padding-right: 20rpx;
		height: 100%;
		display: flex;
		flex: 1;
	}
	.chatInterface .scroll-view{
		flex: 1;
		overflow: auto;
		box-sizing: border-box;
	}
	.chatInterface .top{
		font-size: 24rpx;
		height: 90rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		-webkit-tap-highlight-color: transparent;
		color: blue;
	}
	.chatInterface .top span{
		text-decoration: underline;
	}

	.chatInterface .message-item{
		max-height: 400rpx;
		margin-top: 40rpx;
		overflow: hidden;
	}
	.chatInterface .avatar{
		width: 80rpx;
		height: 80rpx;
		margin-right:20rpx ;
	}
	.chatInterface .content{
		font-size: 34rpx;
		line-height: 44rpx;
		max-height: 400rpx;
		display: flex;
	}
	.chatInterface .content .pending{
		background: url("../../static/images/pending.gif") no-repeat center;
		background-size: 30rpx;
		width: 30rpx;
		height: 30rpx;
		margin-right: 10rpx;
		flex-grow: 0;
		flex-shrink: 0;
	}
	.chatInterface .content img{
		padding: 16rpx;
		border-radius: 12rpx;
		max-height : 300rpx;
		max-width: 300rpx;
	}
	.chatInterface .content span{
		padding: 16rpx;
		border-radius: 12rpx;
	}

	.chatInterface .message-item.self .avatar{
		margin-left: 20rpx;
	}
	.chatInterface .message-item.self .avatar image{
		width: 100%;
		height: 100%;
	}
	.chatInterface .message-item .avatar image{
		width: 100%;
		height: 100%;
	}
	
	.header{
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 36rpx;
		z-index: 100;
		background: linear-gradient(0deg, #D02129, #D02129), linear-gradient(195.96deg, #F33A3A 9.83%, #D02129 105.7%);
		display: flex;
		color: #ffffff;
		justify-content: center;
		align-content: flex-start;
	}
	.back-btn{
		left:20rpx;
		top:25rpx;
		position: absolute;
		background: url("../../static/images/Arrow-Left.png") no-repeat center;
		background-size: 60%;
		width: 40rpx;
		height: 40rpx;
	}
	.member{
		padding: 20rpx;
	}
	.group-member__item{
		width: 96rpx;
		height: 96rpx;
		border-radius: 48rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}
	.layer-header{
		z-index: 9999;
		position: relative;
	}
</style>
